<?php
	require_once("include/common.php");
?>



<!DOCTYPE html>
<html lang="en" ng-app="deviceApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">

<title>用户管理</title>

	<?php
		require_once("pages/resources.php");
	?>
<!-- 
	<link href="/meter/resources/bootstrap-3.3.6/css/bootstrap.min.css" rel="stylesheet">
 -->
	<script src="/meter/resources/jquery/jquery-2.0.3.js"></script>
	<script src="/meter/resources/js/jquery.jeditable.lk.js"></script>
 	<script src="/meter/resources/angular-1.5.5/angular.js"></script>
 	<script src="/meter/resources/js-base-util.js"></script>
 	<script type="text/javascript" src="/meter/resources/layer/layer.js"></script>
 
</head>
<body class="sidebar-narrow"  id="deviceCtrl" ng-controller="deviceCtrl">

	<!-- Navbar -->
	 
	<?php
		require_once("pages/navbar.php");
	?>
	<!-- /navbar -->


	<div class="page-container sidebar-hidden">

		<!-- Sidebar -->
		 
		<?php
			require_once("pages/siderbar.php");
		?>
		<!-- /sidebar -->


		<!-- Begin: Content -->
		<div class="page-content">
			 
			<div class="row" style="margin-top:10px; margin-bottom: 24px">
				 

				<div style="float: left; width: 40%">
	                <div class="input-group">
	                      <span class="input-group-addon" id="basic-addon2"> 用户名称 </span>
	                  	<input type="text" class="form-control" placeholder="Search"
	                                ng-model="uq"
	                                ng-change="user_change()" aria-describedby="basic-addon2">
	                </div>
	            </div> 
	          	<div style="float: right; width: 10%">
	                <div class="input-group">
	                   
	                  	 <button type="button" ng-click="showNewUserDialog();" class="btn btn-default">New User</button>
	                </div>
	            </div> 
	            
	        </div>
	        <div class="row">
	        	 
	            	<table class="table table-striped table-bordered" >
						<thead>
							<tr>
								<td class="col-md-1">标示 </td>
								<td class="col-md-1">名称</td>
								<td class="col-md-1">ENABLE</td>
								<td class="col-md-1">标签</td>
								<td class="col-md-2">更新</td>  
								<td class="col-md-2">同步</td>  
								<td class="col-md-2">读取时间</td>  
								<td class="col-md-1">读数</td>  
								<td class="col-md-1">操作</td>  
						    </tr>
						</thead>
						<tbody>

							<tr ng-repeat="user in users">
								<td >
									<a href="user-data.php?uid={{user._USERID}}" target="_blank" >
										{{user._USERID}}
									</a>
								</td>
					    		<td  >
					    			
					    			{{user._NAME}} 
					    			
					    		</td>
					    		<td ng-style=" { color: user._ENABLE ? '' : 'darkgrey'  }" >  {{user._ENABLE ? '启用' : '停用'}} </td>
					    		<td >{{user._TAGS}}</td>
					    		<td >{{user._UPDATED}}</td>
					    		<td >{{user._SYNC}}</td>
					    		<td >{{user._LAST}}</td>
					    		<td >{{user._VALUE}}</td>
					    		<td>
					    			<center>
						    			<a href="#" ng-click="removeUser(user._USERID)">
						    				<i class="icon-remove"></i>
						    			</a>
						    			&nbsp;&nbsp;
						    			<a href="#" ng-click="showDialog(user._USERID);" title="编辑租户信息"> <i class="icon-wrench2"></i> </a>

					    			</center>

				    				 
				    			</td> 
					    	</tr>
						</tbody>					
					</table>

					<div style="float: left; margin-top:20px" >
	                    <span  id="basic-addon1"> 上传Excel文件（<a href="templates/USERS.xls">下载模板</a>） </span>
	                  	 
						<div id="uploadDiv">
	                  		<input type="file"   title="上传文件" name="file" size="50" onchange="uploadFiles();">
						</div>
						 
	                </div>
			 
	        </div>
	        
			

		</div>
		<!-- End: Content -->

 			
		 <!-- Footer -->
	         
        <?php
			require_once("pages/footer.php");
		?>
        <!-- /footer -->

	</div>

	<div style="position: fixed; bottom: 0px ; right: 0px; z-index: 999">
             
        <span id="responseId" class="label ">
            success!
        </span>
      
    </div>

</body>
<script type="text/javascript">

	var users =  null;

	function response_status( command , result ){
		if(result.status == 0 ){
			$('#responseId').removeClass('label-warning');
			$('#responseId').addClass('label-success');
			$('#responseId').text( 'success! ' + command);
		}else {
			$('#responseId').removeClass('label-success');
			$('#responseId').addClass('label-warning');
			
			$('#responseId').text( 'Error : ' + result.status + ' ' + result.message + '\n' + command );
		}
	}
	
	 

    var app = angular.module('deviceApp', []);
    app.controller('deviceCtrl', 
    	function($scope, $http, $interval) {
    		$scope.uq = '';
        	$scope.q = '' ;
         	$scope.user = null;
        	$scope.users =  [] ; 
    
            $scope.getMeter = function(meterId){
            	for (var i = 0; i < $scope.devices.length; i++) {
            		if( meterId == $scope.devices[i]._METER) {
            			return $scope.devices[i];
            		}
            	}
            	return null;
            }
			$scope.removeUser = function(user){
				var index = layer.confirm('您正在试图删除用户 ' + user + '， 这种操作是不可逆的，你要继续吗? <br/>(可以在编辑页面 下选择disable user)', {
				  btn: ['是的','取消'] //按钮
				}, function(){
					layer.close(index);
				  	$scope.removeUser0(user);
				}, function(){
				  
				});
			} 		
 			$scope.removeUser0 = function(user){

 				

 				var clear = ( $scope.user == user );
	  			var url = '/meter/rest/disp.php?m=userremove'  ;
                // var url = "/rest/api/data/devRT?" ;

				url = _appendUrlList( url, "user" , user );
			        
                
                $http.get( url )
                    .success(
                        function(response) 
                        {
                        	response_status( 'remove user :' + user  ,  response );
                            $scope.loadUsers (clear );

                        
                        }
              	);

	  		}

	  	 
	  	 	$scope.showNewUserDialog =function(){
                _showDialog('');
            }
	  		
            $scope.showDialog =function(userId){
                _showDialog(userId);
            }
	  		$scope.user_change= function(){
         		 
              	$scope.loadUsers(
              	 
              		);
            }  
         
            $scope.loadUsers = function( clear ) {
                
            
 
                var url = '/meter/rest/disp.php?m=userlist'  ;
                url = _appendUrlList( url, "q" , $scope.uq  );  
                $http.get( url )
                    .success(
                        function(response) 
                        {
                        	if( clear  ){
	                        	$scope.user = null;
		  						$scope.q = '' ;
		  						$scope.devices =[];
	                    	}

                            $scope.execResult = response.status ;
                            
                            response_status( 'Loading userlist ' , response );

                            if( response.status != 0 )
                            {
                                return ;
                            }

                            response = JSON.retrocycle(response);
                            $scope.users = response.result;
                           

                        }
              );
            };   

             

            
                // init 
            $scope.loadUsers(true);
           
  
        });

   

    function uploadFiles() {
   		var file = $('input[name="file"').get(0).files[0];
   		if( !file )
   			return ;
		var formData = new FormData();
		formData.append('file', file);

		var htmlv = $('#uploadDiv').html();
		$('#uploadDiv').html(htmlv);
		
		$.ajax({
		  url : '/meter/rest/disp.php?m=upload_users',
		  type : 'POST',
		  data : formData,
		  cache : false,
		  contentType : false,
		  processData : false,
		  success : function( result , textStatus, jqXHR) {
		   // var result = JSON.parse(jqXHR.responseText);
		    // alert(userObj);
		    if(result.status == 0 ){
		    	reloadUser();
		    }else {
		    	alert( result.message );
		    }
		  },
		  error : function(jqXHR, textStatus, errorThrown) {
		    alert(textStatus);
		  }
		});
    }


    function reloadUser(  ){
        var ctrl = angular.element('#deviceCtrl');
        var $scope= ctrl.scope();
 
        $scope.loadUsers(true);
    }


	function _showDialog(user){
	    
	    var url = "user-edit.php?id=" + user ;
	    layer.open({
	      type: 2,
	      title: user ? '编辑租户信息' : '新增用户',
	      shadeClose: true,
	      shade: 0.8,
	      area: ['800px', '50%'],
	      content: [ url ,'no'  ] //iframe的url
	    });
	   
	}


</script>
</html>
